package com.itheima.rpc.client.proxy;

import com.itheima.rpc.client.request.RpcRequestManager;
import com.itheima.rpc.data.RpcRequest;
import com.itheima.rpc.data.RpcResponse;
import com.itheima.rpc.spring.SpringBeanFactory;
import com.itheima.rpc.util.GlobalIDGenerator;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @description
 * @author: ts
 * @create:2021-05-12 00:11
 */
@Slf4j
public class CglibProxyCallBackHandler implements MethodInterceptor {


    public Object intercept(Object o, Method method, Object[] parameters, MethodProxy methodProxy) throws Throwable {
        log.info("进入代理类intercept方法=================");
        if (ReflectionUtils.isObjectMethod(method)) {
            //放过toString,hashcode，equals等方法，采用spring工具类
            return method.invoke(method.getDeclaringClass().newInstance(),parameters);
        }

        //构建请求
        RpcRequest request = new RpcRequest();
        request.setRequestId(GlobalIDGenerator.getInstance().nextStrId());
        request.setClassName(method.getDeclaringClass().getName());
        request.setMethodName(method.getName());
        request.setParameterTypes(method.getParameterTypes());
        request.setParameters(parameters);

        //发起请求
        RpcRequestManager bean = SpringBeanFactory.getBean(RpcRequestManager.class);
        if (ObjectUtils.isEmpty(bean)) {
            log.info("ioc RpcRequestManager 不存在");
        }
        RpcResponse response = bean.sendRequest(request);
        return response.getResult();
    }
}
